#include "comm.hpp"
#include "log.hpp"

void getMessage(int fd)
{
    char buffer[SIZE];
    while (true)
    {
        memset(buffer, '\0', sizeof buffer);
        ssize_t s = read(fd, buffer, sizeof(buffer) - 1);
        if (s < 0)
        {
            perror("read");
            exit(3);
        }
        else if (s > 0)
        {
            cout << "[" << getpid() << "]" << "client say:>" << buffer << endl;
        }
        else
        {
            cout << "[" << getpid() << "]" << "read end of file " << endl;
            break;
        }
       
    }
}

int main()
{
    // 1.创建管道文件
    int ret = mkfifo(ipcName.c_str(), MODE);
    assert(ret == 0);
    (void)ret;
    log("创建管道文件成功", DEBUG) << "step 1" << endl;
    // 2.打开文件，以写的方式
    int fd = open(ipcName.c_str(), O_RDONLY);
    if (fd < 0)
    {
        perror("open");
        exit(1);
    }
    log("打开管道文件成功", DEBUG) << "step 2" << endl;

    // 3.读取内容
    int num = 3;
    for(int i = 0;i < num;i++)
    {
        pid_t id = fork();
        if(id == 0)
        {
            // 3.1让子进程进行读取
            getMessage(fd);
            exit(2);
        }
    }
    for(int i = 0;i < num;i++)
    {
        waitpid(-1,nullptr,0);
    }

    // 4.关闭fd
    close(fd);
    log("关闭管道文件成功", DEBUG) << "step 3"<< endl;

    unlink(ipcName.c_str());
    log("删除管道文件成功", DEBUG) << "step 4"<< endl;

    return 0;
}